var app = getApp();
var wxCharts = require('../../utils/wxcharts.js');
var common = require('../common/common.js')
var bmap = require('../common/bmap-wx.js');
var url = app.globalData.url;
var error = common.error;
var lineChart = null;
var lineChart1 = null;
var lineChart2 = null;
var lineChart3 = null;
var weatherInfor;
var weatherData1;
var weatherData2;
Page({
  data: {
    navbar: ['今日', '本周', '本月', '本年'],
    currentTab: 0,
    isMainChartDisplay: true,
    //总列表循环
    twoList: [{
        id: 1,
        bgcolor: '#2fa5fd',
        icon: 'icon-huikuikehusongliuliang',
        textIcon: '客流量',
        count: '0',
        rise: '0'
      },
      {
        id: 2,
        bgcolor: '#0cd6b0',
        icon: 'icon-waizongfuwu_huishuaichaxun',
        textIcon: '服务率',
        count: '0',
        rise: '0'
      },
      {
        id: 3,
        bgcolor: '#ffb03a',
        icon: 'icon-kaidan_h',
        textIcon: '开单数',
        count: '0',
        rise: '0'
      },
      {
        id: 4,
        bgcolor: '#ff5e87',
        icon: 'icon-chengjiaowanchengshuai',
        textIcon: '成交率',
        count: '0',
        rise: '0'
      },
    ],
  },
  /**
   * navbarTap()点击今日/本周/本月/本年
   */
  navbarTap: function(e) {
    this.setData({
      currentTab: e.currentTarget.dataset.idx
    })
    var that = this
    that.statisticData();
  },
  /**
   * 触摸|点击图表显示数据
   * @param 
   */
  touchHandler: function(e) {
    console.log('今日触屏')
    console.log(e)
    console.log(lineChart.getCurrentDataIndex(e));
    lineChart.showToolTip(e, {
      // background: '#7cb5ec',
      format: function(item, category) {
        return category + ':00' + ' ' + item.name + ':' + item.data
      }
    });
  },
  touchHandler2: function(e) {
    console.log('本周触屏')
    console.log(e)
    console.log(lineChart1.getCurrentDataIndex(e));
    lineChart1.showToolTip(e, {
      // background: '#7cb5ec',
      format: function(item, category) {
        return category + ' ' + item.name + ':' + item.data
      }
    });
  },
  touchHandler3: function(e) {
    console.log('本周触屏')
    console.log(e)
    console.log(lineChart2.getCurrentDataIndex(e));
    lineChart2.showToolTip(e, {
      // background: '#7cb5ec',
      format: function(item, category) {
        return category + ' ' + item.name + ':' + item.data
      }
    });
  },
  touchHandler4: function(e) {
    console.log('本年触屏')
    console.log(e)
    console.log(lineChart3.getCurrentDataIndex(e));
    lineChart3.showToolTip(e, {
      format: function(item, category) {
        return category + ' ' + item.name + ':' + item.data
      }
    });
  },
  // 今日
  createSimulationData: function() {
    var categories = [];
    var data = [];
    for (var i = 8; i < 24; i++) {
      //categories.push('2016-' + (i + 1));
      categories.push(i + 1);
      data.push(Math.random() * (20 - 10) + 10);
    }
    // data[4] = null;
    return {
      categories: categories,
      data: data
    }
  },
  //本周
  createSimulationDataWeek: function() {
    var categories = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    var data = [];
    return {
      categories: categories,
      data: data
    }
  },
  //本月
  createSimulationDataMonth: function() {
    var categories = [];
    var data = [];
    for (var i = 0; i < 5; i++) {
      categories.push('第' + (i + 1) + '周');
      //categories.push(i + 1);
      data.push(Math.random() * (20 - 10) + 10);
    }
    data[4] = null;
    return {
      categories: categories,
      data: data
    }
  },
  //本年
  createSimulationDataYear: function() {
    var categories = [];
    var data = [];
    for (var i = 0; i < 4; i++) {
      categories.push('第' + (i + 1) + '季');
      data.push(Math.random() * (20 - 10) + 10);
    }
    return {
      categories: categories,
      data: data
    }
  },
  onLoad: function(options) {
    console.log(options);
    var that = this;
    clearTimeout(timer); //清除没执行的timer定时器
    var timer = setTimeout(() => {
      that.statisticData(); //加载统计数据信息
    }, 500);

    /** 
     * 获取系统信息 
     */
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
  },
  /**
   * 统计摘要数据
   * 
   */
  statisticData: function() {
    var that = this;
    var currentTab = that.data.currentTab;
    // 页面初始化，接收登录页面所传来的参数
    var user = wx.getStorageSync('account');
    var pwd = wx.getStorageSync('password');
    var Token = wx.getStorageSync('Token');
    var locIDs = wx.getStorageSync('dayShopIdStr');
    var CurentTime = common.CurentTime();
    console.log(that.data.locIDs)
    that.setData({
      user: user,
      pwd: pwd,
      Token: Token,
      currentTime: CurentTime,
      locIDs: locIDs
    });
    var params = {
      Token: Token,
      Type: currentTab,
      WithSalesData: true,
      WithComparedData: true,
      WithWeatherData: true,
      LocationIDs: locIDs
    }
    that.getChartData(params, currentTab); //调用图表数据
    that.getSumData(params, currentTab); //调用统计数据

  },
  /**
   * 请求图表数据
   */
  getChartData(params, currentTab) {
    var that = this;
    common.requestLoading(url + '/data', params, '正在加载数据', function(res) {
      wx.hideLoading();
      console.log(res)
      var basic = res.BasicData;
      var counts = basic.CustTrafficData; //客流量
      var sales = basic.SalesData; // 下单数
      var WCustTrafficArr = [];
      var WcountsArr = [];
      var windowWidth = 320;
      try {
        var res = wx.getSystemInfoSync();
        windowWidth = res.windowWidth;
      } catch (e) {
        console.error('getSystemInfoSync failed!');
      }

      function timesDataKey(times, counts, WCustTrafficArr, sales) {
        for (var i = 0; i < counts.length; i++) {
          var lab = counts[i].LABEL;
          var n = times.indexOf(lab);
          WCustTrafficArr[n] = counts[i].IN; //客流量

        }
        for (var j = 0; j < sales.length; j++) {
          var saleTime = sales[j].LABEL;
          var time = times.indexOf(saleTime);
          WcountsArr[time] = sales[j].Counts; //下单数
        }
      }
      switch (currentTab) {
        case 0:
          var Arr = ['09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'];
          var simulationData = that.createSimulationData().categories;
          timesDataKey(Arr, counts, WCustTrafficArr, sales);
          common.calUndefined(WCustTrafficArr);
          common.calUndefined(WcountsArr);
          console.log(WcountsArr)
          lineChart = that.Chart('lineCanvas', simulationData, WCustTrafficArr, WcountsArr, windowWidth);
          break;
        case 1:
          var dateArr = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']; //本周
          var simulationData1 = that.createSimulationDataWeek().categories;
          timesDataKey(dateArr, counts, WCustTrafficArr, sales)
          common.calUndefined(WCustTrafficArr);
          common.calUndefined(WcountsArr);
          lineChart1 = that.Chart('lineCanvas1', simulationData1, WCustTrafficArr, WcountsArr, windowWidth);
          break;
        case 2:
          var weekArr = ['1', '2', '3', '4', '5']; //本月核对
          var simulationData2 = that.createSimulationDataMonth().categories;
          timesDataKey(weekArr, counts, WCustTrafficArr, sales)
          common.calUndefined(WCustTrafficArr);
          common.calUndefined(WcountsArr);
          lineChart2 = that.Chart('lineCanvas2', simulationData2, WCustTrafficArr, WcountsArr, windowWidth);
          break;
        case 3:
          var yearArr = ['1', '2', '3', '4'];
          var simulationData3 = that.createSimulationDataYear().categories;
          timesDataKey(yearArr, counts, WCustTrafficArr, sales)
          common.calUndefined(WCustTrafficArr);
          common.calUndefined(WcountsArr);
          lineChart3 = that.Chart('lineCanvas3', simulationData3, WCustTrafficArr, WcountsArr, windowWidth);
          break;
      }




    }, error)
  },
  /**
   *请求统计数据 
   */
  getSumData(params, currentTab) {
    var that = this;
    common.requestLoading(url + '/sumdata', params, '正在加载数据', function(res) {
      //res就是我们请求接口返回的数据
      console.log(res)
      weatherInfor = res.WeatherData;
      wx.hideLoading();
      //处理天气数据
      weatherData1 = weatherInfor.slice(0, 3)
      weatherData2 = weatherInfor.slice(3, 5)

      var SumData = res.SumData;
      var countsData = SumData.CustTrafficData.Basic.IN; //客流量
      var serviceData = SumData.StaffData.Basic; //服务人员
      var sales = SumData.SalesData.Basic.Counts; //开单数

      var countsCom = SumData.CustTrafficData.Compared.IN; //比较客流量
      var serviceCom = SumData.StaffData.Compared; //比较服务人员
      var salesCom = SumData.SalesData.Compared.Counts; //比较开单数

      var serviceRateData = Math.ceil(countsData / serviceData); //同期服务率
      var serviceRateDataCom = Math.ceil(countsCom / serviceCom); //比较服务率
      var dealRate = common.call(sales, countsData); //同期成交率
      var dealRateCom = common.call(salesCom, countsCom); //比较成交率
      /*
       *判断非空、未定义、null 
       */
      function dataNull(data) {
        if (typeof data == 'number' || isNaN(data)) {
          data = 0
        }
        return data
      }
      //相对应的值转化
      sales = dataNull(sales);
      dealRate = dataNull(dealRate);
      countsData = dataNull(countsData);
      serviceRateData = dataNull(serviceRateData);
      /**
       * 增长率
       */
      var countsRate = common.compareVal(countsData, countsCom); //客流量增长率
      var serveRate = common.compareVal(serviceRateData, serviceRateDataCom); //服务率增长率
      var billingsRate = common.compareVal(sales, salesCom); //开单数增长率
      var dealsRate = common.compareVal(dealRate, dealRateCom); //成交率增长率
      //var counts = that.data.twoList[0].count
      function fourData(data, i) {
        var counts = data + "[" + i + "].count"
        return counts
      }

      function riseData(data, i) {
        var rateCounts = data + "[" + i + "].rise"
        return rateCounts
      }

      function y_Statistics() {
        that.setData({
          [fourData('twoList', 0)]: common.format_number(countsData),
          [fourData('twoList', 1)]: common.format_number(serviceRateData),
          [fourData('twoList', 2)]: common.format_number(sales),
          [fourData('twoList', 3)]: dealRate + '%',
          [riseData('twoList', 0)]: countsRate,
          [riseData('twoList', 1)]: serveRate,
          [riseData('twoList', 2)]: billingsRate,
          [riseData('twoList', 3)]: dealsRate,
          weatherData1: weatherData1,
          weatherData2: weatherData2
        });
      }
      const comparativeTotles = new Map([
        [0, y_Statistics()],
        [1, y_Statistics()],
        [2, y_Statistics()],
        [3, y_Statistics()]
      ])
      comparativeTotles.get(currentTab);
    }, error)

  },
  /**
   * 提示功能（提示当前时间无数据）
   * 提示客流量并且开单数无数据的话，会出现提示：
   */
  showModeTime: function() {
    wx.showModal({
      title: '提示',
      content: '当前时间暂无数据信息，请稍后重试！',
      showCancel: false,
      success: function(res) {
        if (res.confirm) {
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  /**
   * 例如chart1图表数据，chart2图表数据
   * 图表填充数据
   */
  Chart: function(canvasId, categories, WCustTrafficArr, WcountsArr, windowWidth) {
    return new wxCharts({
      canvasId: canvasId,
      type: 'line',
      categories: categories,
      animation: true,
      dataLabel: true,
      // background: '#f5f5f5',
      series: [{
          name: '客流量',
          //data: simulationData.data,
          data: !WCustTrafficArr.length ? this.showModeTime() : WCustTrafficArr,
          //dataLabel: true,
          format: function(val, name) {
            return val;
          }
        },
        {
          name: '开单数',
          data: !WcountsArr.length ? new Array(WCustTrafficArr.length).fill(0) : WcountsArr,
          format: function(val, name) {
            return val;
          }
        },
        /* {
          name: '成交率(%)',
          data: rate,
          format: function (val, name) {
            return val;
          }
        } */
      ],
      xAxis: {
        disableGrid: true
      },
      yAxis: {
        // title: '成交金额 (万元)',
        format: function(val) {
          return val.toFixed(2);
        },
        min: 0,
        disabled: true
      },
      width: windowWidth,
      height: 260,
      dataPointShape: true,
      extra: {
        lineStyle: 'curve'
      }
    });
  }
});